package com.spic.business.train.prepare.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.spic.business.train.createtest.domain.TrainExam;
import com.spic.business.train.createtest.mapper.TrainExamMapper;
import com.spic.business.train.examination.domain.TrainPaper;
import com.spic.business.train.examination.mapper.TrainPaperMapper;
import com.spic.business.train.prepare.domain.TrainExamUserState;
import com.spic.business.train.prepare.dto.ExamDetailRespDTO;
import com.spic.business.train.prepare.dto.ExamResultDTO;
import com.spic.business.train.prepare.dto.PaperAnSwerDTO;
import com.spic.business.train.prepare.enums.QuType;
import com.spic.business.train.prepare.mapper.TrainExamUserStateMapper;
import com.spic.business.train.prepare.service.ITrainPrepareService;
import com.spic.business.train.questions.domain.TrainQuestions;
import com.spic.business.train.questions.domain.TrainQuestionsOptions;
import com.spic.business.train.questions.mapper.TrainQuestionsMapper;
import com.spic.business.train.questions.mapper.TrainQuestionsOptionsMapper;
import com.spic.business.train.questions.service.ITrainQuestionsService;
import com.spic.business.train.trainUserAnswer.domain.TrainUserAnswer;
import com.spic.business.train.trainUserAnswer.mapper.TrainUserAnswerMapper;
import com.spic.common.core.utils.SecurityUtils;
import com.spic.common.core.utils.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 开始考试Service业务层处理
 *
 * @author yangjie
 * @date 2021-10-21
 */
@Service
public class TrainPrepareServiceImpl implements ITrainPrepareService
{
    @Autowired
    private TrainQuestionsMapper trainQuestionsMapper;
    @Autowired
    private TrainExamMapper trainExamMapper;
    @Autowired
    private TrainPaperMapper trainPaperMapper;
    @Autowired
    private ITrainQuestionsService trainQuestionsService;
    @Autowired
    private TrainQuestionsOptionsMapper trainQuestionsOptionsMapper;
    @Autowired
    private TrainUserAnswerMapper trainUserAnswerMapper;

    @Autowired
    private TrainExamUserStateMapper trainExamUserStateMapper;

    /**
     * 查询题库管理
     * @param id 题库管理主键
     * @return 题库管理
     */

    @Override
    public TrainQuestions selectTrainQuestionsById(String id)
    {
        TrainQuestions questions = trainQuestionsMapper.selectTrainQuestionsByIdAll(id);
        return questions;
    }

    /**
     * 查询题库管理列表
     * @param examId 考试id
     * @return 题库管理
     */

    @Override
    public List<TrainQuestions> selectTrainQuestionsList(Long examId,Long userId)
    {

        List<TrainQuestions> trList = new ArrayList<>();
        TrainPaper trainPaper = new TrainPaper();
        trainPaper.setExamId(examId);
        trainPaper.setUserId(userId);
        List<TrainPaper> trainPaperList = trainPaperMapper.selectTrainPaperList(trainPaper);
        for(TrainPaper tr:trainPaperList){
            String questionId =  tr.getQuestionsId();
            TrainQuestions questions = trainQuestionsMapper.selectTrainQuestionsByIdAll(questionId);
            trList.add(questions);
        }
        return trList;
    }
    /**
     * 根据考试id查询试卷表
     * @param examId
     * @return
     */
    @Override
    public List<TrainPaper> selectPaperlistByExamId(Long examId)
    {
        Long userId = SecurityUtils.getUserId();
        TrainPaper trainPaper = new TrainPaper();
        trainPaper.setExamId(examId);
        trainPaper.setUserId(userId);
        List<TrainPaper> trainPaperList = trainPaperMapper.selectTrainPaperList(trainPaper);
        return trainPaperList;
    }

    //根据考试id sort 查询  examId    sort
    @Override
    public PaperAnSwerDTO selectquestionsByExamAndSort(PaperAnSwerDTO paperAnSwerDTO)
    {
        Long userId = SecurityUtils.getUserId();
        PaperAnSwerDTO anSwerDTO = new PaperAnSwerDTO();
        Long examId = paperAnSwerDTO.getExamId();
        String sort = paperAnSwerDTO.getSort();
        QueryWrapper<TrainPaper> trainPaperwrapper=new QueryWrapper<>();
        trainPaperwrapper.eq("exam_id",examId);
        trainPaperwrapper.eq("sort",sort);
        trainPaperwrapper.eq("user_id",userId);
        List<TrainPaper> paperList = trainPaperMapper.selectList(trainPaperwrapper);
        if(paperList!=null && paperList.size()>0){
            TrainPaper paper = paperList.get(0);
            Long paperId = paper.getId(); //试卷ID
            anSwerDTO.setQuestionsId(paper.getQuestionsId());
            anSwerDTO.setQuType(paper.getQuType());
            anSwerDTO.setSort(paper.getSort());
            anSwerDTO.setFraction(paper.getFraction());

            TrainUserAnswer userAnswer = new TrainUserAnswer();
            userAnswer.setUserId(userId);
            userAnswer.setPaperId(paperId+"");
            List<TrainUserAnswer> userAnswersList = trainUserAnswerMapper.selectTrainUserAnswerList(userAnswer);
            if(userAnswersList!=null && userAnswersList.size()>0){
                TrainUserAnswer trainUserAnswer = userAnswersList.get(0);
                anSwerDTO.setAnswer(trainUserAnswer.getAnswer());
                anSwerDTO.setAnswered(trainUserAnswer.getAnswered());
            }
        }

        return anSwerDTO;
    }

    /**
     * 新增或者更新  用户试卷答案表
     * @param paperAnSwerDTO
     */
    @Override
    public void updatePaperByExamAndSort(PaperAnSwerDTO paperAnSwerDTO)
    {
        Long userId = SecurityUtils.getUserId();
        String answered = paperAnSwerDTO.getAnswered();
        String answer = paperAnSwerDTO.getAnswer();
        Double fraction = paperAnSwerDTO.getFraction();
        Long examId = paperAnSwerDTO.getExamId();
        String quType = paperAnSwerDTO.getQuType();
        String questionsId = paperAnSwerDTO.getQuestionsId();
        String sort = paperAnSwerDTO.getSort();

        //根据考试id和题号 查询试卷TrainPaper
        QueryWrapper<TrainPaper> trainPaperwrapper=new QueryWrapper<>();
        trainPaperwrapper.eq("exam_id",examId);
        trainPaperwrapper.eq("sort",sort);
        trainPaperwrapper.eq("user_id",userId);
        List<TrainPaper> paperList = trainPaperMapper.selectList(trainPaperwrapper);
        if(paperList!=null && paperList.size()>0){
            TrainPaper paper = paperList.get(0);
            Long paperId = paper.getId(); //试卷ID
            int judge = -1;
            if(StringUtils.isNotEmpty(answer)){
                QueryWrapper<TrainQuestionsOptions> wrapper=new QueryWrapper<>();
                String qusetAnswer = "";
                //单选 判断
                if(QuType.RADIO.equals(quType) || QuType.JUDGE.equals(quType)){
                    wrapper.eq("id",answer);
                    TrainQuestionsOptions trainQuestionsOptions = trainQuestionsOptionsMapper.selectOne(wrapper);
                    qusetAnswer =  trainQuestionsOptions.getOptionsKey();
                }else if(QuType.MULTI.equals(quType)){ //多选
                    if(answer.indexOf(",")!=-1){
                        List<String>  newsAnswer= Arrays.asList(answer.split(","));
                        wrapper.in("id",newsAnswer);
                    }else{
                        wrapper.eq("id",answer);
                    }
                    List<TrainQuestionsOptions> trainQuestionsOptions = trainQuestionsOptionsMapper.selectList(wrapper);
                    for (TrainQuestionsOptions questionsOption : trainQuestionsOptions)
                    {
                        qusetAnswer += questionsOption.getOptionsKey();
                    }
                }else if(QuType.GAP.equals(quType)){ //填空
                    qusetAnswer = answer;
                }
                Double scoreProportion = trainQuestionsService.selectTrainQuestionsScoreProportion(questionsId, qusetAnswer);
                Double score = fraction*scoreProportion; //分数
//            0 对 1 错 2未选全
                if(score.doubleValue()>0){
                    if(fraction==score.doubleValue()){
                        judge = 0;
                    }else{
                        judge=2;
                    }
                }else{
                    judge=1;
                }

                /**
                 *  判断 用户答案表是否有此记录
                 */
                TrainUserAnswer userAnswer = new TrainUserAnswer();
                userAnswer.setUserId(userId);
                userAnswer.setPaperId(paperId+"");
                List<TrainUserAnswer> userAnswersList = trainUserAnswerMapper.selectTrainUserAnswerList(userAnswer);

                if(userAnswersList!=null && userAnswersList.size()>0){
                    TrainUserAnswer trainUserAnswerupdate = userAnswersList.get(0);
                    trainUserAnswerupdate.setJudge(judge); //0 对 1 错 2未选全
                    trainUserAnswerupdate.setActualScore(score); //实际分数
                    trainUserAnswerupdate.setAnswer(answer); //答案
                    trainUserAnswerupdate.setAnswered(answered); //是否已答
                    trainUserAnswerMapper.updateTrainUserAnswer(trainUserAnswerupdate);
                }else{
                    TrainUserAnswer trainUserAnswerInsert = new TrainUserAnswer();
                    String s = IdWorker.get32UUID().replaceAll("-", "");
                    trainUserAnswerInsert.setId(s);
                    trainUserAnswerInsert.setPaperId(paperId+"");
                    trainUserAnswerInsert.setUserId(userId);
                    trainUserAnswerInsert.setJudge(judge); //0 对 1 错 2未选全
                    trainUserAnswerInsert.setActualScore(score); //实际分数
                    trainUserAnswerInsert.setAnswer(answer); //答案
                    trainUserAnswerInsert.setAnswered(answered); //是否已答
                    trainUserAnswerMapper.insertTrainUserAnswer(trainUserAnswerInsert);
                }
            }
        }

    }

    @Override
    public ExamDetailRespDTO paperDetail(Long id)
    {
        Long userId = SecurityUtils.getUserId();
        ExamDetailRespDTO respDTO = new ExamDetailRespDTO();
        TrainPaper trainPaper = new TrainPaper();
        trainPaper.setExamId(id);
        trainPaper.setUserId(userId);

        // 试题基本信息
        List<TrainPaper> trainPapers = trainPaperMapper.selectTrainPaperList(trainPaper);
        // 查找题目列表
        List<TrainPaper> radioList = new ArrayList<>();
        List<TrainPaper> multiList = new ArrayList<>();
        List<TrainPaper> judgeList = new ArrayList<>();
        List<TrainPaper> gapList = new ArrayList<>();
        for(TrainPaper item: trainPapers){
            if(QuType.RADIO.equals(item.getQuType())){
                radioList.add(item);
            }
            if(QuType.MULTI.equals(item.getQuType())){
                multiList.add(item);
            }
            if(QuType.JUDGE.equals(item.getQuType())){
                judgeList.add(item);
            }
            if(QuType.GAP.equals(item.getQuType())){
                gapList.add(item);
            }
        }
        radioList.sort((x,y)->Integer.compare(Integer.parseInt(x.getSort()),Integer.parseInt(y.getSort())));
        multiList.sort((x,y)->Integer.compare(Integer.parseInt(x.getSort()),Integer.parseInt(y.getSort())));
        judgeList.sort((x,y)->Integer.compare(Integer.parseInt(x.getSort()),Integer.parseInt(y.getSort())));
        gapList.sort((x,y)->Integer.compare(Integer.parseInt(x.getSort()),Integer.parseInt(y.getSort())));
        respDTO.setRadioList(radioList);
        respDTO.setMultiList(multiList);
        respDTO.setJudgeList(judgeList);
        respDTO.setGapList(gapList);
        return respDTO;
    }

    /**
     * 判分
     * @param id 题库管理主键
     * @param answer 作答答案
     * @param  examId  考试id
     * @return 题库改题得分比例
     */
    @Override
    public Double selectTrainQuestionsScoreProportion(Long examId,String id, String answer)
    {
        Long userId = SecurityUtils.getUserId();
        //得分比例
        Double scoreProportion = trainQuestionsService.selectTrainQuestionsScoreProportion(id, answer);
        QueryWrapper<TrainPaper> wrapper=new QueryWrapper<>();
        wrapper.eq("exam_id",examId);
        wrapper.eq("questions_id",id);
        wrapper.eq("user_id",userId);
        List<TrainPaper> trainPaperList = trainPaperMapper.selectList(wrapper);
        if(trainPaperList!=null&& trainPaperList.size()>0){
            TrainPaper trainPaper = trainPaperList.get(0);
            Double score = trainPaper.getFraction()*scoreProportion; //分数
            return score;
        }
        return 0d;
    }

    @Override
    public List<Map<String, Object>> criticalScore(TrainPaper trainPaper)
    {
        trainPaper.getExamId();
        return null;
    }

    //获取考试结束试卷
    @Override
    public HashMap<String ,Object> selectTrainExamResultList(Long examId,Long userId)
    {
        HashMap<String ,Object> examResultDTOListMap = new HashMap<>();
        List<ExamResultDTO> examResultDTOList = new ArrayList<>();
        List<TrainQuestions> trainQuestions = selectTrainQuestionsList(examId,userId);
        TrainExam trainExam = trainExamMapper.selectTrainExamById(examId);
        String actualTime = "";
        String duration = "";
        String tital = "";
        if (null != trainExam){
            duration  = trainExam.getDuration();
            tital = trainExam.getTitle();
        }

        double totalScore = 0d;
        int nextVal = 0;
        AtomicInteger val = new AtomicInteger(nextVal);
        for (TrainQuestions questions :trainQuestions){
            QueryWrapper<TrainQuestionsOptions> wrapper=new QueryWrapper<>();
            ExamResultDTO examResultDTO = new ExamResultDTO();
            String id = questions.getId();
            BeanUtils.copyProperties(questions,examResultDTO);
            TrainPaper trainPaper = new TrainPaper();
            trainPaper.setExamId(examId);
            trainPaper.setQuestionsId(id);
            trainPaper.setUserId(userId);
            List<TrainPaper> trainPapers = trainPaperMapper.selectTrainPaperList(trainPaper);
            if(trainPapers!=null && trainPapers.size()>0){
                TrainPaper paper = trainPapers.get(0);
                TrainUserAnswer userAnswer = new TrainUserAnswer();
                userAnswer.setUserId(userId);
                userAnswer.setPaperId(paper.getId()+"");
                List<TrainUserAnswer> userAnswersList = trainUserAnswerMapper.selectTrainUserAnswerList(userAnswer);
                String answer ="";
                double antualScore = 0d;
                if(userAnswersList!=null && userAnswersList.size()>0){
                    TrainUserAnswer trainUserAnswer = userAnswersList.get(0);
                    Integer judge = trainUserAnswer.getJudge();
                    if(judge==0){ // 对
                        nextVal = val.incrementAndGet();
                    }
                    answer = trainUserAnswer.getAnswer();
                    antualScore = trainUserAnswer.getActualScore();
                    actualTime = trainUserAnswer.getActualTime();
                    examResultDTO.setActualScore(antualScore+"");//题目得分
                    examResultDTO.setIsRight(trainUserAnswer.getJudge()); //题目是否答对
                    examResultDTO.setAnswer(answer); //题目答案
                    examResultDTO.setAnswered(trainUserAnswer.getAnswered()); //题目是否已答
                }

                String quType = paper.getQuType();

                examResultDTO.setQuestionsId(paper.getQuestionsId()); //题库id
                examResultDTO.setExamId(paper.getExamId()); //考试id
                examResultDTO.setQuType(paper.getQuType());  //题目类型
                examResultDTO.setSort(paper.getSort()); //题目排序
                examResultDTO.setFraction(paper.getFraction()); //题目分数

                examResultDTOList.add(examResultDTO);
                String qusetAnswer = "";
                if(StringUtils.isNotEmpty(answer)){
                    if(QuType.RADIO.equals(quType) || QuType.JUDGE.equals(quType)){
                        wrapper.eq("id",answer);
                        TrainQuestionsOptions trainQuestionsOptions = trainQuestionsOptionsMapper.selectOne(wrapper);
                       if (null != trainQuestionsOptions){
                           qusetAnswer =  trainQuestionsOptions.getOptionsKey();
                       }
                    }else if(QuType.MULTI.equals(quType)){ //多选
                        if(answer.indexOf(",")!=-1){
                            List<String>  newsAnswer= Arrays.asList(answer.split(","));
                            wrapper.in("id",newsAnswer);
                        }else{
                            wrapper.eq("id",answer);
                        }
                        List<TrainQuestionsOptions> trainQuestionsOptions = trainQuestionsOptionsMapper.selectList(wrapper);
                        for (TrainQuestionsOptions questionsOption : trainQuestionsOptions)
                        {
                            qusetAnswer += questionsOption.getOptionsKey();
                            qusetAnswer += ",";

                        }
                        if (qusetAnswer.endsWith(","))
                        {
                             qusetAnswer = qusetAnswer.substring(0,qusetAnswer.length()-1) ;
                        }
                    }else if(QuType.GAP.equals(quType)){ //填空

                    }
                }

                examResultDTO.setAnswerCode(qusetAnswer);
                totalScore += antualScore;
            }
        }
        examResultDTOListMap.put("examResult",examResultDTOList);
        examResultDTOList.sort((x,y)->Integer.compare(Integer.parseInt(x.getSort()),Integer.parseInt(y.getSort())));
        examResultDTOListMap.put("totalScore",totalScore);
        examResultDTOListMap.put("examContent",tital);
        examResultDTOListMap.put("correctQuestionCount",nextVal); //正确题数
        examResultDTOListMap.put("errorQuestionCount",examResultDTOList.size() - nextVal); //错题数
        examResultDTOListMap.put("actualTime",actualTime); //考试时长
        examResultDTOListMap.put("duration",duration); //总时长
        examResultDTOListMap.put("userName", userId+"");
        return examResultDTOListMap;
    }

    @Override
    public Map<String,Object> selectPaperQuestionsByExamId(Long examId)
    {
        Long userId = SecurityUtils.getUserId();
        TrainExam trainExam = trainExamMapper.selectTrainExamById(examId);
        Map<String,Object> result = new HashMap<>();
        TrainPaper trainPaper = new TrainPaper();
        trainPaper.setExamId(examId);
        trainPaper.setUserId(userId);
        List<TrainPaper> trainPaperList = trainPaperMapper.selectTrainPaperList(trainPaper);
        List<TrainQuestions> questionsList = new ArrayList<>();
        for (TrainPaper paper : trainPaperList)
        {
            Double fraction = paper.getFraction();
            String questionsId = paper.getQuestionsId();
            TrainQuestions questions = trainQuestionsMapper.selectTrainQuestionsByIdAll(questionsId);
            questions.setFraction(fraction);
            questionsList.add(questions);
        }
        List< Map<String,Object> >  blankArr =  new ArrayList<>();
        result.put("resultQuestions",questionsList);
        result.put("resultExam",trainExam);
        result.put("blankArr",blankArr);

        return result;
    }


    public static void main(String[] args)
    {
        Long a = new Long(100);
        Double b = new Double(0.33D);
        System.out.println(a*b);
    }
    //查询考试详情校验 是否考完试
    @Override
    public TrainExamUserState trainExamUserStateByFinsh(Long examId,Long userId){
        QueryWrapper<TrainExamUserState> sectionQueryWrapper = new QueryWrapper<>();
        sectionQueryWrapper.eq("train_user_id",userId);
        sectionQueryWrapper.eq("exam_id",examId);
        List<TrainExamUserState> trainExamUserStates = trainExamUserStateMapper.selectList(sectionQueryWrapper);
        if(trainExamUserStates!=null && trainExamUserStates.size()>0){
            return trainExamUserStates.get(0);
        }
        return null;
    }
}
